import { getUserInfo } from '@/services/user'
import { useUserStore, useUserStores } from '@/stores'

export const usrloging = (): Promise<boolean> => {
  const store = useUserStore()
  const stores = useUserStores()
  const url = window.location.href
  const hashIndex = url.indexOf('#')

  return new Promise((resolve, reject) => {
    if (hashIndex !== -1) {
      const hash = url.slice(hashIndex + 1) // 获取哈希部分
      const urlParams = new URLSearchParams(hash.split('?')[1]) // 获取查询字符串部分
      const id = urlParams.get('id')
      stores.getId(id)
    } else {
      console.log('URL 中没有哈希部分')
    }
    // 请求用户 ID
    const requestUserId = () => {
      const u = navigator.userAgent
      if (u.includes('Android') || u.includes('Linux')) {
        ;(window as any).zafu?.requestInfoFromApp()
      } else if (/\(i[^;]+;( U;)? CPU.+Mac OS X/.test(u)) {
        window.webkit?.messageHandlers?.requestInfoFromApp?.postMessage(null)
      }
    }

    // 获取追踪编号
    const getTrackingNumber = async (authCode: any) => {
      try {
        const res = await getUserInfo({
          authCode
        }) // 这里是接口
        if (res.code == 200) {
          stores.addUsr(res.data.access_token)
          store.apps('co')
          resolve(true) // 成功获取到用户信息，解析 Promise
        } else {
          resolve(false) // 未成功获取到用户信息，解析 Promise
        }
      } catch (error) {
        console.error('Failed to get token:', error)
        reject(error) // 捕获错误，拒绝 Promise
      }
    }

    // 检查是否为 App 登录
    const isAppLogin = (): boolean => {
      const u = navigator.userAgent
      if (u.includes('Android') || u.includes('Linux')) {
        return !!(window as any).zafu?.requestInfoFromApp
      } else if (/\(i[^;]+;( U;)? CPU.+Mac OS X/.test(u)) {
        return !!window.webkit?.messageHandlers?.requestInfoFromApp
      }
      return false
    }

    // 登录逻辑
    const checkAppLogin = isAppLogin()
    if (checkAppLogin) {
      ;(window as any).getTrackingNumber = getTrackingNumber
      ;(window as any).infoFromApp = (info: any) => {
        const res = JSON.parse(info)
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            const { data } = JSON.parse(xhr.responseText)
            console.log('获取到的authcode:', data)
            getTrackingNumber(data)
          }
        }
        const urlAuth = 'https://app.zafu.edu.cn/app/app/authcode.jhtm'
        xhr.open(
          'POST',
          `${urlAuth}?userId=${res.userId}&t=${Math.random()}`,
          true
        )
        xhr.send()
      }
      requestUserId()
    } else {
      resolve(false) // 非 App 登录，直接解析 Promise 为 false
    }
  })
}
